package bank_access;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class Kommunikationsmodul {

    private String host;
    private int port;
    private Socket socket;
    private BufferedReader dataIn;
    private DataOutputStream dataOut;
    private static Logger logger;

    public Kommunikationsmodul(String host, int port) {
        logger = getLogger();
        this.host = host;
        this.port = port;
//        initSocket();
    }

    private void initSocket() {
        try {
            socket = new Socket(host, port);
            dataIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            dataOut = new DataOutputStream(socket.getOutputStream());
        } catch (UnknownHostException e) {
            logger.severe("UnknownHostException " + e);
        } catch (IOException e) {
            logger.severe("IOException " + e);
        }
    }

    /**
     * Baue Verbindung zum Port und Host auf und schicke die Nachricht
     * @param message
     * @return
     */
    public String send(String message) {
        initSocket();
        try {
            dataOut.writeBytes(message);
            return dataIn.readLine();
        } catch (IOException e) {
            logger.severe("EXCEPTION Kommunikationsmodul::einzahlen ** " + e);
        } catch (NumberFormatException e) {
            logger.severe("EXCEPTION Kommunikationsmodul::einzahlen ** " + e);
        }
        return null;
    }

    public static Logger getLogger() {
        FileHandler fhandler = null;
        if (logger == null) {
            try {
                fhandler = new FileHandler("Bank_Access.log");
                fhandler.setFormatter(new SimpleFormatter());
                logger = Logger.getLogger("Bank_Access");
                logger.addHandler(fhandler);
                logger.setLevel(Level.INFO);
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return logger;
    }
}
